/**
 * Created by XGJ on 2017/10/17.
 */

import {Directive, ElementRef, Renderer2, Input} from "@angular/core";
import {Content} from "ionic-angular";

@Directive({
    selector:'[stickyAndroid]'
})

    export class StickyAndroidDirective{
    private originDomTop:number;
    @Input()
    content:Content; //存放数据的model

    constructor(
        public el:ElementRef,   //操作DOM的API
            protected renderer:Renderer2){
    }


    ngAfterViewInit(){
        let ele = this.el.nativeElement; //获取到ion-item-divider元素。
        let partent = this.renderer.parentNode(ele);//获取到的父节点。
        //添加一个div
        let supportHolde = this.renderer.createElement('div');
        let clientHeight = ele.clientHeight + 'px'; //获取到ion-item-divider元素的高度
        this.renderer.insertBefore(partent,supportHolde,ele); //在已有的子节点前添加一个新的接点。
        this.originDomTop = ele.offsetTop;  //获取对象相对于由offsetParent属性指定的父坐标(css定位的元素或body元素)距离顶端的高度。
        // 监听滚动事件
        this.content.ionScroll.subscribe(($event:any)=>{
            let top = $event.scrollTop; //滚动后被隐藏区域
            if(top > this.originDomTop){
                this.renderer.setStyle(ele,'position','fixed');
                this.renderer.setStyle(ele,'top','44px');
                console.log(333);
                this.renderer.setStyle(supportHolde,'height',clientHeight);
            }else{
                this.renderer.removeStyle(ele,'position');
                this.renderer.removeStyle(ele,'top');
                this.renderer.setStyle(supportHolde,'height','0');
            }

        })

    }

}
